<template>
	<div class="map-container-wrapper">
	  <div class="search-container">
		<el-autocomplete
		  v-model="companyName"
		  placeholder="输入公司全称"
		  :fetch-suggestions="querySearch"
		  @select="handleSelect"
		  class="search-input"
		  @keyup.enter.native="handleConfirm"
		>
		  <template #append>
			<el-button icon="el-icon-search" @click="handleConfirm" />
		  </template>
		</el-autocomplete>
	  </div>
  
	  <div id="map-container" ref="mapContainer"></div>
	</div>
  </template>
  
  <script>
  import AMapLoader from '@amap/amap-jsapi-loader'
  import { result } from 'lodash';
  import {ref} from "vue";
  
  window._AMapSecurityConfig = {
	securityJsCode: '2b06d933467ca1ee8950bbe7aacfee84'
  }
  
  export default {
	props: ['msg'],
	data() {
	  return {
		disc: '',
		map: null,
		placeSearch: null,
		companyName: '',
		lng: '',
		lat: '',
		address: '',
		suggestions: [],
		locating: false,
		currentLocation: null,
		result1: null,
		row: null,
	  }
	},
	mounted() {
	  this.initMap()
	},
	methods: {
	  initMap: async function () {
		try {
		  const AMap = await AMapLoader.load({
			key: '36aa605b5ec2faae32b4e82b22c3c573',
			version: '2.0',
			plugins: [
			  'AMap.PlaceSearch',
			  'AMap.AutoComplete',
			  'AMap.Geolocation',
			  'AMap.Geocoder'
			]
		  })
  
		  this.map = new AMap.Map('map-container', {
			zoom: 15,
			resizeEnable: true
		  })
  
		  this.placeSearch = new AMap.PlaceSearch({
			city: '太原',
			pageSize: 5,
			map: this.map
		  })
  
		  this.placeSearch.on('complete', this.handleSearchComplete)
  
		  this.geolocation = new AMap.Geolocation({
			enableHighAccuracy: true,
			timeout: 10000,
			showButton: true,
		  })
  
		  this.geocoder = new AMap.Geocoder({
			city: "全国"
		  })
		  
		  var res = await this.$API.system.attendConfig.getAttendConfigById.get({configId: this.msg});
		  this.result1 = res;
		  this.disc = res.data.disc
		  this.locateCurrentPosition();
		} catch (error) {
		  console.error('地图初始化失败:', error)
		}
	  },
  
	  locateCurrentPosition() {
		this.geolocation.getCurrentPosition((status, result) => {
		  if (result.position !== undefined) {
			this.lng = result.position.getLng()
			this.lat = result.position.getLat()  
		  }	
		  if(this.result1.data !== undefined) {
			this.lng = this.result1.data.lon
			this.lat = this.result1.data.lat
		  }
		  if (this.lng !== '' && this.lat != '') {
			this.map.setCenter([this.lng, this.lat]);
			new AMap.Marker({
			  position: [this.lng, this.lat],
			  map: this.map
			});
			this.park()  
		  }
		})
	  },
  
	  async park(){
		const circle = new AMap.Circle({
		  center: [this.lng, this.lat],
		  radius: this.disc,
		  strokeColor: "#335fff",
		  strokeOpacity: 0.8,
		  strokeWeight: 2,
		  fillColor: "#1791fc",
		  fillOpacity: 0.3,
		});
		circle.setMap(this.map);
		this.map.setFitView([circle], { zoom: 16 });
		this.map.setZoomAndCenter(15, [this.lng, this.lat]);
	  },
  
	  async querySearch(queryString, cb) {
		if (!queryString) return cb([])
		try {
		  const autoComplete = new AMap.AutoComplete({
			city: '全国'
		  })
  
		  autoComplete.search(queryString, (status, result) => {
			if (status === 'complete') {
			  this.suggestions = result.tips.map(item => ({
				value: item.name,
				address: item.address || item.district,
				...item
			  }))
			  cb(this.suggestions)
			}
		  })
		} catch (error) {
		  console.error('建议查询失败:', error)
		  cb([])
		}
	  },
  
	  handleSelect(item) {
		this.companyName = item.value
		this.handleConfirm()
	  },
  
	  handleConfirm() {
		if (!this.companyName) return
		this.placeSearch.search(this.companyName)
	  },
  
	  handleSearchComplete(data) {
		this.map.clearMap()
		if (data.poiList && data.poiList.pois.length) {
		  const firstResult = data.poiList.pois[0]
		  this.lng = firstResult.location.lng.toFixed(6)
		  this.lat = firstResult.location.lat.toFixed(6)
		  this.address = firstResult.address || firstResult.name
  
		  this.map.setCenter(firstResult.location)
		  new AMap.Marker({
			position: firstResult.location,
			map: this.map
		  })
		  
		  this.$emit('success', {
			lng: this.lng,
			lat: this.lat,
			address: this.address
		  });
		  
		  this.park()
		} else {
		  this.$message.warning('未找到匹配结果')
		}
	  }
	}
  }
  </script>
  
  <style scoped>
  .map-container-wrapper {
	display: flex;
	flex-direction: column;
	height: 100%;
	padding: 20px;
	box-sizing: border-box;
  }
  
  .search-container {
	display: flex;
	justify-content: center;
	margin-bottom: 20px;
  }
  
  .search-input {
	width: 100%;
	max-width: 500px;
  }
  
  #map-container {
	flex: 1;
	min-height: 400px;
	border: 1px solid #e4e7ed;
	border-radius: 4px;
	box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }
  
  /* Responsive adjustments */
  @media (max-width: 768px) {
	.map-container-wrapper {
	  padding: 10px;
	}
	
	#map-container {
	  min-height: 300px;
	}
  }
  </style>